<template>
  <div>
    <Form ref="form" :rules="formValidate" :label-width="90" :model="form">
          <FormItem label="姓名" prop="name">
            <Input v-model="form.name" />
          </FormItem>
          <FormItem label="录取院校" prop="college">
            <Input v-model="form.college" />
          </FormItem>
          <FormItem label="录取专业" prop="specialty">
            <Input v-model="form.specialty" />
          </FormItem>
          <FormItem label="攻读学位" prop="degree">
            <Input v-model="form.degree" />
          </FormItem>
          <FormItem label="奖学金" prop="financialAid">
            <Input v-model="form.financialAid" type="number"/>
          </FormItem>
          <FormItem label="教育背景" prop="educationBackground">
            <Input v-model="form.educationBackground" type="textarea" :rows="3"/>
          </FormItem>
          <FormItem label="托福成绩" prop="toeflScore">
            <Input v-model="form.toeflScore" type="number"/>
          </FormItem>
          <FormItem label="雅思成绩" prop="ieltsScore">
            <Input v-model="form.ieltsScore" type="number"/>
          </FormItem>
          <FormItem label="GRE成绩" prop="greScore">
            <Input v-model="form.greScore" type="number"/>
          </FormItem>
          <FormItem>
              <Upload
              multiple
              accept="image/png, image/jpeg"
              :action="uploadUrl"
              :headers="uploadHeader"
              :onError="uploadError"
              :onSuccess="uploadSuccess"
              :on-preview="preview"
              :on-remove="removePicture"
              :showUploadList="true"
              :default-file-list="form.studentProductVOs"
            >
              <Button icon="ios-cloud-upload-outline" type="primary">上传作品</Button>
            </Upload>
          </FormItem>
    </Form>
    <Row class="code-row-bg" justify="end" type="flex">
      <Button @click="cancel" style="margin-right:10px">取消</Button>
      <Button @click="save" type="primary">保存</Button>
    </Row>

    <Modal title="图片预览" 
           v-model="previewModel.show"
           cancel-text="">
      <img :src="previewModel.imageUrl" v-if="previewModel.show" style="width: 100%">
    </Modal>
  </div>
</template>
<script>
  import { studentApi } from '@/api/student';
  import { fileApi } from '@/api/file';
  import Cookies from 'js-cookie';
  import { TOKEN_KEY } from '@/lib/cookie';
  export default {
    name: 'StudentListForm',
    components: {
    },
    props: {
      //是否为更新表单
      isUpdate: {
        type: Boolean,
        default: true
      },
      //更新的表单数据对象
      updateData: {
        type: Object
      }
    },
    data() {
      return {
        //表单数据
        form: {
         name:null,
         college:null,
         specialty:null,
         degree:null,
         financialAid:null,
         educationBackground:null,
         toeflScore:null,
         ieltsScore:null,
         greScore:null,
         pictureIds:[],
         studentProductVOs:[]
        },
        //表单验证
        formValidate: {
        //学生姓名
        name:[{ required: true, message: '请输入姓名', trigger: 'blur' }]
        },
        // 图片预览窗口可见
        previewModel: {
          show: false
        }
      };
    },
  watch: {
      updateData: function(newValue, oldValue) {
          this.$refs['form'].resetFields();
          if (this.isUpdate) {
              for (let k in this.form) {
                  this.$set(this.form, k, newValue[k]);
              }
              this.$set(this.form, 'id', newValue['id']);
              this.$set(this.form, 'pictureIds', []);
              this.$set(this.form, 'studentProductVOs', newValue['studentProductVOs']);
          }
      },
      isUpdate: function(newValue, oldValue) {
          if (!newValue) {
              this.resetForm();
              this.$refs['form'].resetFields();
          }
      }
  },
  computed: {
    uploadHeader: function() {
      let header = {
        'x-access-token': Cookies.get(TOKEN_KEY)
      };
      return header;
    },
    uploadUrl: function() {
      let baseUrl = fileApi.fileUploadLocalUrl;
      let url = baseUrl + 1;
      return url;
    }
  },
    created() {},
    mounted() {
      
    },
    methods: {
      // 上传成功钩子
      async uploadSuccess(e) {
        if (!e.success) {
          console.error(e);
          return this.uploadError();
        }
        this.$Spin.show();
        let reqBody = {
          moduleId: 1,
          moduleType: 1,
          fileLocationType: 1,
          fileName: e.data.fileName,
          filePath: e.data.filePath
        };
        let rep = await fileApi.addFile(reqBody);
        this.form.pictureIds.push(rep.data);
        this.$Spin.hide();
        this.$Message.success('上传成功');
        // this.find();
      },
      // 上传失败钩子
      uploadError(e) {
        this.$Message.error('上传出错，请重试！');
        console.error(e);
        this.find();
      },
      preview(file) {
        this.previewModel.show = true;
        if (this.isUpdate) {
          this.previewModel.imageUrl = file.url;
        } else {
          this.previewModel.imageUrl = file.response.data.url;
        }
      },
      removePicture(file) {
        this.remove(file.name);
      },
      cancel() {
        this.$emit('on-form-close');
      },
      save() {
       this.$refs['form'].validate(valid => {
         if (valid) {
           if (this.isUpdate) {
            this.update();
           } else {
             this.add();
           }
         } else {
          this.$Message.error('参数验证错误，请仔细填写表单数据!');
         }
       });
      },
    resetForm() {
        this.form = {
            name:null,
            college:null,
            specialty:null,
            degree:null,
            financialAid:null,
            educationBackground:null,
            toeflScore:null,
            ieltsScore:null,
            greScore:null,
            pictureIds:[]
        };
        this.$refs['form'].resetFields();
      },
      async add() {
        this.$Spin.show();
        let res = await studentApi.addStudent(this.form);
        this.$Message.success(res.msg);
        this.$Spin.hide();
        this.resetForm();
        this.$emit('on-form-close');
      },
      async update() {
        this.$Spin.show();
        let res = await studentApi.updateStudent(this.form);
        this.$Message.success(res.msg);
        this.$Spin.hide();
        this.resetForm();
        this.$emit('on-form-close');
      },
      async remove(fileName) {
        this.$Spin.show();
        let res = await studentApi.deleteProduct(fileName);
        this.$Message.success(res.msg);
        this.$Spin.hide();
      }
    }
  };
</script>